package dao.daoImp;

import bean.ClassBean;
import bean.StudentBean;
import dao.IClassDao;
import dao.IStudentDao;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class StudentDaoImp extends BaseDao implements IStudentDao {
    IClassDao iClassDao=new ClassDaoImp();
    @Override
    public void createStu() {

        this.setConnection();
        try {
            ps=con.prepareStatement("CREATE TABLE t_student(" +
                    "pk_studentId INT PRIMARY KEY AUTO_INCREMENT," +
                    "s_studentName VARCHAR(20)," +
                    "fk_classId INT"+
                    ");" );

            ps.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            this.closeConnection();
        }
    }

    @Override
    public void add(StudentBean studentBean) {
        this.setConnection();

        try {
            ps = con.prepareStatement("INSERT INTO t_student(pk_studentId,s_studentName,fk_classId)" +
                    "values (?,?,?)");

            ps.setObject(1, studentBean.getStudentId());
            ps.setObject(2, studentBean.getStudentName());
            ps.setObject(3,studentBean.getClassBean().getClassId());

            ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeConnection();
        }
    }

    @Override
    public List<StudentBean> findAll() {
        List<StudentBean> list = new ArrayList<>();
        this.setConnection();
        try {
            ps = con.prepareStatement("select * from t_student");
            rs = ps.executeQuery();

            while (rs.next()) {
                StudentBean studentBean=new StudentBean();
                studentBean.setStudentId(rs.getInt("pk_studentId"));
                studentBean.setStudentName(rs.getString("s_studentName"));
                studentBean.setClassBean(iClassDao.findById(rs.getInt("fk_classId")));

                list.add(studentBean);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.closeConnection();
        }
        return list;
    }
}
